package com.dhms.vostok1.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.dhms.home.databinding.HomeTodayCircleTodoItemBinding
import com.dhms.home.databinding.HomeTodayTodoItemBinding
import com.dhms.vostok1.data.StatisticsType
import com.dhms.vostok1.data.ToDoStatisticsItem
import com.dhms.vostok1.utils.Utils


class TodoListStatisticsViewPager(
    private val listData: List<ToDoStatisticsItem>,
    private val goToDoClick: (() -> Unit)? = null
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    class PagerViewHolder(var binding: HomeTodayTodoItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ToDoStatisticsItem) {
            binding.item = item
            binding.executePendingBindings()
        }
    }

    class CirclePagerViewHolder(var binding: HomeTodayCircleTodoItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: ToDoStatisticsItem) {
            binding.item = item
            val progress = Utils.getPercentage(item.data.doneCount, item.data.total)
            binding.progressBar1.progress = progress
            binding.todayTodoTitleTextView.text = "$progress%"
            binding.executePendingBindings()
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder {
        return when (StatisticsType.fromInt(viewType)) {
            StatisticsType.LINE_PROGRESS -> PagerViewHolder(
                HomeTodayTodoItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            )
            StatisticsType.CIRCLE_PROGRESS -> CirclePagerViewHolder(
                HomeTodayCircleTodoItemBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        }
    }


    override fun getItemCount(): Int {
        return listData.size
    }

    override fun getItemViewType(position: Int): Int {
        val record = listData[position]
        return record.type.value
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val record = listData[position]
        when (record.type) {
            StatisticsType.LINE_PROGRESS -> {
                (holder as PagerViewHolder).bind(record)
                (holder as PagerViewHolder).binding.goToDoButton.setOnClickListener {
                    goToDoClick?.let {
                        it()
                    }
                }
            }
            StatisticsType.CIRCLE_PROGRESS -> (holder as CirclePagerViewHolder).bind(record)
        }
    }
}
